import type {ArticleType, Effect,Reducer} from 'umi';
import {addArticle,updateArticle,productArticle as findArticleApi} from '@/services/article';
import { message } from 'antd';
// react组件需要用,所以单独导出
export type StateType = {
  article: ArticleType;
}
type MType = {
  namespace: string;
  state: StateType;
  reducers: {
    setArticle: Reducer;
  };
  effects: {
    saveArticle: Effect;
    findArticle: Effect;
  }
}

const M: MType = {
  namespace: 'articleEdit',
  state: {
    article: {
      author: '',
      title: '',
    }
  },
  reducers: {
    setArticle(state,{payload: {article}}){
      return {
        ...state,
        article
      }
    }
  },
  effects: {
    /**
     * 合并更新和新增, 区别是新增没有id,更新有id
     * @param param0 
     * @param param1 
     */
    *saveArticle({payload:{submitFormValue,callback}},{call}){
      // 判断是更新还是新增
      const api = submitFormValue.id? updateArticle: addArticle;
      // console.log(' submitFormValue.id', submitFormValue.id)
      const {success,message:errMsg} = yield call(api,submitFormValue);
      if(success){
        // 提示保存成功!
        message.success(submitFormValue.id?'更新成功!':'保存成功!');
        // 回调 从外部处理成功后的业务逻辑,比如关闭表单,清空表单,刷新数据列表
        callback();
      }else{
        message.error(errMsg);
      }
      // console.log(rs);
    },
    *findArticle({payload},{call,put}){
      const {id} = payload;
      const {success,message:errMsg,data} = yield call(findArticleApi,id);
      if(success){
        // console.log(data);
        const {productArticle} = data;
        // 特别注意: put需要yield修饰 要不然无效!
        yield put({
          type: 'setArticle',
          payload: {
            article: productArticle
          }
        })
      }else{
        message.error(errMsg);
      }
    }
  }
}

export default M;